package com.example.receiptocr.home

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import java.math.BigDecimal
import androidx.compose.ui.graphics.Color
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.receiptocr.bodys.responseBodys.ReceiptInfo
import com.example.receiptocr.viewModels.DetailsViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReceiptDetailsScreen(
    receiptInfo: ReceiptInfo,
    viewModel: DetailsViewModel = hiltViewModel(),
    onNavigateBack: () -> Unit = {},
    onSaveAndReturn: () -> Unit = {}
) {
    Box(modifier = Modifier.fillMaxSize()) {

    var receiptInfoRemember by remember { mutableStateOf(receiptInfo) }
    var receiptDataListRemember by remember { mutableStateOf(receiptInfo.receiptDataList)}

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("编辑票据") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, "返回")
                    }
                }
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
                .padding(bottom = 80.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 基本信息部分
            item {
                Text(
                    text = "票据基本信息",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                EditableInfoItem(
                    label = "票据名称",
                    value = receiptInfo.receiptName.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(receiptName = newValue)
                    }
                )

                EditableInfoItem(
                    label = "票据代码",
                    value = receiptInfo.receiptCode.toString(),
                    onValueChange = { newValue ->
                        try {
                            receiptInfoRemember = receiptInfo.copy(receiptCode = newValue.toLong())
                        } catch (e: Exception) {
                            // 处理转换错误
                        }
                    }
                )

                EditableInfoItem(
                    label = "票据号码",
                    value = receiptInfo.receiptNumber.toString(),
                    onValueChange = { newValue ->
                        try {
                            receiptInfoRemember = receiptInfo.copy(receiptNumber = newValue.toLong())
                        } catch (e: Exception) {
                            // 处理转换错误
                        }
                    }
                )

                EditableInfoItem(
                    label = "票据时间",
                    value = receiptInfo.receiptDate.toString(),
                    onValueChange = { newValue ->
                        // 这里可以添加日期选择器的逻辑
                        // 暂时保持原值
                    }
                )
            }

            // 购买方信息
            item {
                Text(
                    text = "购买方信息",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(vertical = 8.dp)
                )

                EditableInfoItem(
                    label = "名称",
                    value = receiptInfo.purchaserName.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(purchaserName = newValue)
                    }
                )
                EditableInfoItem(
                    label = "纳税人识别号",
                    value = receiptInfo.purchaserCode.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(purchaserCode = newValue)
                    }
                )
                EditableInfoItem(
                    label = "地址和电话",
                    value = receiptInfo.purchaserAddress.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(purchaserAddress = newValue)
                    }
                )
                EditableInfoItem(
                    label = "开户行及账号",
                    value = receiptInfo.purchaserBank.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(purchaserBank = newValue)
                    }
                )
            }

            // 销售方信息
            item {
                Text(
                    text = "销售方信息",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(vertical = 8.dp)
                )

                EditableInfoItem(
                    label = "名称",
                    value = receiptInfo.sellerName.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(sellerName = newValue)
                    }
                )
                EditableInfoItem(
                    label = "纳税人识别号",
                    value = receiptInfo.sellerCode.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(sellerCode = newValue)
                    }
                )
                EditableInfoItem(
                    label = "地址和电话",
                    value = receiptInfo.sellerAddress.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(sellerAddress = newValue)
                    }
                )
                EditableInfoItem(
                    label = "开户行及账号",
                    value = receiptInfo.sellerBank.toString(),
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(sellerBank = newValue)
                    }
                )
            }

            // 项目信息
            item {
                Text(
                    text = "项目明细",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(vertical = 8.dp)
                )
            }

            // 项目卡片列表
            items(receiptDataListRemember) { projectData ->
                com.example.receiptocr.ocr.EditableProjectCard(
                    projectData = projectData,
                    onProjectDataChange = { newProjectData ->
                        val index = receiptDataListRemember.indexOf(projectData)
                        receiptDataListRemember = receiptDataListRemember.toMutableList().apply {
                            set(index, newProjectData)
                        }
                    }
                )
            }

            // 总计信息
            item {
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                EditableInfoItem(
                    label = "总金额",
                    value = receiptInfo.totalAmount.toString(),
                    onValueChange = { newValue ->
                        try {
                            receiptInfoRemember = receiptInfo.copy(totalAmount = newValue.toDouble())
                        } catch (e: Exception) {
                            // 处理转换错误
                        }
                    }
                )
                EditableInfoItem(
                    label = "备注",
                    value = receiptInfo.note ?: "",
                    onValueChange = { newValue ->
                        receiptInfoRemember = receiptInfo.copy(note = newValue)
                    }
                )
            }
        }
    }

    // 保存按钮
    Button(
        onClick = {
            receiptInfo.let { viewModel.saveReceipt(it,) }
            onSaveAndReturn()
        },
        modifier = Modifier
            .align(Alignment.BottomEnd)
            .padding(16.dp)
            .height(48.dp)
    ) {
        Text("确认保存")
    }
}
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditableInfoItem(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.weight(1f)
        )
        TextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier
                .weight(2f)
                .padding(start = 16.dp),
            textStyle = MaterialTheme.typography.bodyLarge,
            colors = TextFieldDefaults.colors(
                focusedContainerColor = Color.Transparent,
                unfocusedContainerColor = Color.Transparent,
                disabledContainerColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                cursorColor = MaterialTheme.colorScheme.primary
            ),
            singleLine = true
        )
    }
}

@Composable
fun EditableProjectCard(
    projectData: ReceiptData,
    onProjectDataChange: (ReceiptData) -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            EditableInfoItem(
                label = "项目名称",
                value = projectData.projectName,
                onValueChange = { newValue ->
                    onProjectDataChange(projectData.copy(projectName = newValue))
                }
            )
            EditableInfoItem(
                label = "规格",
                value = projectData.projectSpecs,
                onValueChange = { newValue ->
                    onProjectDataChange(projectData.copy(projectSpecs = newValue))
                }
            )
            EditableInfoItem(
                label = "单价",
                value = projectData.unitPrice.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(unitPrice = newValue.toDouble()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "数量",
                value = projectData.quantity.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(quantity = newValue.toLong()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "金额",
                value = projectData.amount.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(amount = newValue.toDouble()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "税率",
                value = projectData.taxRate.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(taxRate = newValue.toLong()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "税款",
                value = projectData.taxPayment.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(taxPayment = newValue.toDouble()))
                    } catch (e: Exception) {}
                }
            )
        }
    }
}

data class ReceiptData(
    val projectName: String,
    val projectSpecs: String,
    val unitPrice: Double,
    val quantity: Long,
    val amount: Double,
    val taxRate: Long,
    val taxPayment: Double
)

